package org.springblade.modules.rotation;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Component
@EnableScheduling
public class DynamicScheduler implements SchedulingConfigurer {

    @Resource
//    @Qualifier("orderTaskScheduler")
    private TaskScheduler taskScheduler;
    private final Map<String, ScheduledFuture<?>> taskMap = new ConcurrentHashMap<>();

//    public DynamicScheduler(TaskScheduler taskScheduler) {
//        this.taskScheduler = taskScheduler;
//    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // 初始化时可以添加一些默认任务
    }

    /**
     * 添加/更新定时任务
     * @param taskId 任务ID
     * @param cronExpression cron表达式
     * @param runnable 任务逻辑
     */
    public void addOrUpdateTask(String taskId, String cronExpression, Runnable runnable) {
        // 先取消已存在的任务
        cancelTask(taskId);

        // 创建新的触发器
        CronTrigger trigger = new CronTrigger(cronExpression, TimeZone.getDefault());

        // 调度任务
        ScheduledFuture<?> future = taskScheduler.schedule(runnable, trigger);

        // 保存任务引用
        taskMap.put(taskId, future);
    }

    /**
     * 取消定时任务
     * @param taskId 任务ID
     */
    public void cancelTask(String taskId) {
        ScheduledFuture<?> future = taskMap.get(taskId);
        if (future != null) {
            future.cancel(true);
            taskMap.remove(taskId);
        }
    }

    /**
     * 获取所有任务ID
     */
    public Set<String> getAllTaskIds() {
        return taskMap.keySet();
    }
}
